package com.lijing.mock.manager;

import com.lijing.mock.constract.MongoTableConstant;
import com.lijing.mock.model.ServerResult;
import com.lijing.mock.model.bo.UrlMockBO;
import com.lijing.mock.model.dto.UrlBaseDTO;
import com.lijing.mock.model.dto.UrlMockDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * url mock 配置信息
 * @author by lijing
 * @date 2019/12/3 0003 17:12
 */
@Slf4j
@Component
public class UrlMockManager {

    private final MongoTemplate mongoTemplate;

    public UrlMockManager(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * 保存url mock信息
     * @param urlMock url mock配置信息
     * @return 保存后的url mock信息
     */
    public ServerResult<UrlMockBO> saveOrUpdate(UrlMockBO urlMock){
        //分布式环境需要改为分布式锁，此处单机环境，只是为了保证数据一致性
        synchronized (UrlMockManager.class) {
            try {
                UrlBaseDTO urlBase = mongoTemplate.save(urlMock.getBase(), MongoTableConstant.BASE_URL_CONFIG);
                List<UrlMockDTO> list = urlMock.getList();
                for (UrlMockDTO mockDTO:list) {
                    mockDTO.setUrlId(urlBase.getId());
                    mongoTemplate.save(mockDTO, MongoTableConstant.URL_MOCK_RESULT_DATA);
                }
            }catch (DuplicateKeyException dke){
                log.error("projectName:{},url:{},该数据已存在，请重新配置！",urlMock.getBase().getProjectName(),urlMock.getBase().getUrl());
                return new ServerResult<>(false,"操作失败，数据已存在",null);
            }catch (Exception e){
                log.error("新增或更新url mock信息失败，原因：",e);
                return new ServerResult<>(false,"操作失败，系统异常",null);
            }
            return new ServerResult<>(true,null,urlMock);
        }
    }


    /**
     * 根据urlId查询所有url mock 结果数据配置信息
     * @param urlId urlId
     * @return 查询到的结果数据配置信息
     */
    List<UrlMockDTO> queryByUrlId(String urlId){
        Query query = new Query();
        query.addCriteria(Criteria.where("urlId").is(urlId));
        return mongoTemplate.find(query, UrlMockDTO.class, MongoTableConstant.URL_MOCK_RESULT_DATA);
    }

    /**
     * 根据url 查询所有 url 基本配置信息
     * @param url url信息
     * @return 查询到的url基本配置信息
     */
    List<UrlMockDTO> queryByUrl(String url){
        Query query = new Query();
        query.addCriteria(Criteria.where("url").is(url));
        return mongoTemplate.find(query, UrlMockDTO.class, MongoTableConstant.BASE_URL_CONFIG);
    }


}
